<template>
  <ych-modal
    :fullscreen="true"
    :title="title"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    :cancelText="$t('m.common.button.close')">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row style="width: 100%;">
          <a-col :span="24/2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label="$t('m.system.announcement.entity.titile')">
              <a-input placeholder="" v-decorator="['titile', validatorRules.title]" :disabled="disableSubmit"/>
            </a-form-item>
          </a-col>
          <a-col :span="24/2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label="$t('m.system.announcement.entity.msgCategory')">
              <a-select
                v-decorator="[ 'msgCategory', validatorRules.msgCategory]"
                placeholder=""
                :disabled="disableSubmit"
                :getPopupContainer="(target) => target.parentNode">
                <a-select-option value="1">{{$t('m.system.announcement.other.msgCategory_option1')}}</a-select-option>
                <a-select-option value="2">{{$t('m.system.announcement.other.msgCategory_option2')}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row style="width: 100%;">
          <a-col :span="24/2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label="$t('m.common.label.begin_time')">
              <ych-date :disabled="disableSubmit" style="width: 100%" :getCalendarContainer="node => node.parentNode"
                      v-decorator="[ 'startTime', validatorRules.startTime]" placeholder="" showTime
                      dateFormat="YYYY-MM-DD HH:mm:ss"></ych-date>
            </a-form-item>
          </a-col>
          <a-col :span="24/2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label="$t('m.common.label.end_time')"
              class="endTime">
              <ych-date :disabled="disableSubmit" style="width: 100%" :getCalendarContainer="node => node.parentNode"
                      v-decorator="[ 'endTime', validatorRules.endTime]" placeholder="" showTime
                      dateFormat="YYYY-MM-DD HH:mm:ss"></ych-date>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row style="width: 100%;">
          <a-col :span="24/2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label="$t('m.system.announcement.entity.priority')">
              <a-select
                v-decorator="[ 'priority', {}]"
                placeholder=""
                :disabled="disableSubmit"
                :getPopupContainer="(target) => target.parentNode">
                <a-select-option value="L">{{$t('m.system.announcement.other.priority_option1')}}</a-select-option>
                <a-select-option value="M">{{$t('m.system.announcement.other.priority_option2')}}</a-select-option>
                <a-select-option value="H">{{$t('m.system.announcement.other.priority_option3')}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24/2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label="$t('m.system.announcement.entity.msgType')">
              <a-select
                v-decorator="[ 'msgType', validatorRules.msgType]"
                placeholder=""
                :disabled="disableSubmit"
                @change="chooseMsgType"
                :getPopupContainer="(target) => target.parentNode">
                <a-select-option value="USER">{{$t('m.system.announcement.other.msgType_option1')}}</a-select-option>
                <a-select-option value="ALL">{{$t('m.system.announcement.other.msgType_option2')}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row style="width: 100%;">
          <!--<a-col :span="24/2">-->
            <!--<a-form-item-->
              <!--:labelCol="labelCol"-->
              <!--:wrapperCol="wrapperCol"-->
              <!--label="摘要">-->
              <!--<a-textarea :disabled="disableSubmit" placeholder="请输入摘要" v-decorator="['msgAbstract',validatorRules.msgAbstract]"/>-->
            <!--</a-form-item>-->
          <!--</a-col>-->
          <a-col :span="24/2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label="$t('m.system.announcement.entity.selectedUser')"
              v-if="userType">
              <a-select
                mode="multiple"
                placeholder=""
                v-model="selectedUser"
                @dropdownVisibleChange="selectUserIds"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row style="width: 100%;">
          <a-col :span="24">
            <a-form-item
              :labelCol="labelColX1"
              :wrapperCol="wrapperColX1"
              :label="$t('m.system.announcement.entity.msgContent')"
              class="j-field-content">
              <ych-editor v-decorator="[ 'msgContent', {} ]"></ych-editor>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <select-user-list-modal ref="UserListModal" @choseUser="choseUser"></select-user-list-modal>
  </ych-modal>
</template>

<script>

  import { httpAction } from '@/api/manage'
  import { getAction } from '@/api/manage'
  import SelectUserListModal from './SelectUserListModal'
  import moment from 'moment'
  import YchConstant from "@/api/YchConstant";
  // import YchEditor from '@/components/ych/YchEditor'
  import {YchDate} from '@yuncheng/ych-components'
  import YchOrg from "@/api/YchOrg"

  export default {
    components: {
      SelectUserListModal,
      YchEditor: () => import("@/components/ych/YchEditor"),
      YchDate
    },
    name: 'SysAnnouncementModal',
    data () {
      return {
        title: this.$t('m.common.label.operate'),
        visible: false,
        disableSubmit: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 },
        },
        labelColX1: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperColX1: {
          xs: { span: 24 },
          sm: { span: 21 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          title: { rules: [{ required: true, message: this.$t('m.common.tip.verify_required') }] },
          msgCategory: { rules: [{ required: true, message: this.$t('m.common.tip.verify_required') }] },
          msgType: { rules: [{ required: true, message: this.$t('m.common.tip.verify_required') }] },
          endTime: { rules: [{ required: true, message: this.$t('m.common.tip.verify_required') }, { validator: this.endTimeValidate }] },
          startTime: { rules: [{ required: true, message: this.$t('m.common.tip.verify_required') }, { validator: this.startTimeValidate }] },
          // msgAbstract: { rules: [{ required: true, message: this.$t('m.common.tip.verify_required') }] },
        },
        url: {
          queryByIds: YchOrg.queryUserListByIds,
          add: YchConstant.PREFIX_SYSTEM + '/annountCement/add',
          edit: YchConstant.PREFIX_SYSTEM + '/annountCement/edit',
        },
        userType: false,
        userIds: [],
        selectedUser: [],
        msgContent: '',
        disabled:false
      }
    },
    created () {
    },
    methods: {
      add () {
        this.edit({})
      },
      edit (record) {
        this.form.resetFields()
        this.model = {}
        this.disable = false
        this.visible = true
        this.getUser(record)
      },
      getUser (record) {
        this.model = Object.assign({}, record)
        // 指定用户
        if (record && record.msgType === 'USER') {
          this.userType = true
          this.userIds = record.userIds
          getAction(this.url.queryByIds, { userIds: this.userIds }).then((res) => {
            if (res.success) {
              for (var i = 0; i < res.result.length; i++) {
                this.selectedUser.push(res.result[i].realname)
              }
              this.$refs.UserListModal.edit(res.result, this.userIds)
            }
          })
        }
        this.$nextTick(() => {
          this.form.setFieldsValue(this.lodash.pick(this.model, 'endTime', 'startTime', 'titile', 'msgContent', 'priority', 'msgCategory', 'msgType'))
        })
      },
      close () {
        this.$emit('close')
        this.selectedUser = []
        this.visible = false
      },
      handleOk () {
        const that = this
        //当设置指定用户类型，但用户为空时，后台报错
        if (this.userType && !(this.userIds != null && this.userIds.length > 0)) {
          this.messageUtil.warning(this.$t('m.system.announcement.verify.selectedUser_check'))
          return
        }
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            if (this.userType) {
              formData.userIds = this.userIds
            }
            //console.log(formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.messageUtil.success(res.message)
                that.$emit('ok')
                that.resetUser()
              } else {
                that.messageUtil.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })

          }
        })
      },
      handleCancel () {
        this.visible = false
        this.$emit('close')
        this.resetUser()
      },
      resetUser () {
        this.userType = false
        this.userIds = []
        this.selectedUser = []
        this.disabled = false
        this.$refs.UserListModal.edit(null, null)
      },
      selectUserIds () {
        this.$refs.UserListModal.add(this.selectedUser, this.userIds)
      },
      chooseMsgType (value) {
        if ('USER' == value) {
          this.userType = true
        } else {
          this.userType = false
          this.selectedUser = []
          this.userIds = []
        }
      },
      // 子modal回调
      choseUser: function (userList) {
        this.selectedUser = []
        this.userIds = []
        for (var i = 0; i < userList.length; i++) {
          this.selectedUser.push(userList[i].realname)
          this.userIds += userList[i].id + ','
        }
      },
      startTimeValidate (rule, value, callback) {
        let endTime = this.form.getFieldValue('endTime')
        if (!value || !endTime) {
          callback()
        } else if (moment(value).isBefore(endTime)) {
          callback()
        } else {
          callback(this.$t('m.system.announcement.verify.time_check'))
        }
      },
      endTimeValidate (rule, value, callback) {
        let startTime = this.form.getFieldValue('startTime')
        if (!value || !startTime) {
          callback()
        } else if (moment(startTime).isBefore(value)) {
          callback()
        } else {
          callback(this.$t('m.system.announcement.verify.time_check'))
        }
      }

    }
  }
</script>
